package activities;

import java.io.IOException;
import java.util.List;

import com.iculture.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class GoogleMapActivity extends Activity {
    private GoogleMap gMap;
    private EditText editTextSearchAddress;
    private Button buttonSearchAddress;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_googlemap);
        findView();
        setListenerOrAdapter();
        gMap.setMyLocationEnabled(true);
        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(25.106119, 121.560974), 10));
    }

	private void findView() {
    	gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.gMap)).getMap();
    	editTextSearchAddress = (EditText)findViewById(R.id.editTextSearchAddress);
    	buttonSearchAddress = (Button)findViewById(R.id.buttonSearchAddress);
	}
	
	private void setListenerOrAdapter() {
		editTextSearchAddress.setOnTouchListener(new EditTextSearchAddressTouchListener());
		buttonSearchAddress.setOnClickListener(new ButtonSearchClickListener());
	}
	
	private class EditTextSearchAddressTouchListener implements EditText.OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			editTextSearchAddress.setText("");
			return false;
		}
	}
	
	private class ButtonSearchClickListener implements Button.OnClickListener {

		@Override
		public void onClick(View arg0) {
			Geocoder geocoder = new Geocoder(GoogleMapActivity.this);
	        try {
	        	Address firstAddr;
	        	String searchAddress = editTextSearchAddress.getText().toString();
				List<Address> addrList = geocoder.getFromLocationName(searchAddress, 10);
				
				firstAddr = addrList.get(0);
				for (Address addr: addrList) {
					String addrText = "";
					
					for (int i=0; i<=addr.getMaxAddressLineIndex(); i++)
						addrText += addr.getAddressLine(i);
					gMap.addMarker(new MarkerOptions()
					.position(new LatLng(addr.getLatitude(), addr.getLongitude()))
			        .title(addr.getFeatureName())
			        .snippet(addrText)).showInfoWindow();
				}
				gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(firstAddr.getLatitude(), firstAddr.getLongitude()), 16));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}